<?php defined('SYSPATH') OR die('No direct access allowed.');

class Auth_Controller extends Web_Controller {
  public $template = 'index';

  public function __construct() {
    parent::__construct();
  }

  public function index() {
      $this->user OR url::redirect(url::base(FALSE).'auth/login');
      url::redirect(url::base(FALSE).'auth/profile');
  }

  public function login() {
    $this->user AND url::redirect(url::base(FALSE).'auth/profile');
    $errors = array();
    if ($this->input->post()) {
      // введены данные формы
      if (Auth::instance()->login($_POST['username'], $_POST['password'])) {
        url::redirect(url::base(FALSE).'auth/profile');
      }
      else $errors['login'] = 'login failed!';
    }
    $this->template->content = new View('auth/login');
    $this->template->title = 'Авторизация пользователя';
    $this->template->content->errors = $errors;
  }

    public function logout() {
      $this->user OR url::redirect(url::base(FALSE).'auth/login');
      if (Auth::instance()->logout()) {
        url::redirect(url::base(FALSE).'auth/login');
      }
    }

  public function register() {
    $this->user AND url::redirect(url::base(FALSE).'auth/profile');
    $this->template->title = 'Регистрация нового пользователя';
    $errors = $data = array();
    if ($this->input->post()) {
        // введены данные формы
        $errors = $data = array(
          'email' =>            '',
          'email_confirm' =>    '',
          'username' =>         '',
          'password' =>         '',
          'password_confirm' => '',
        );
        $data = arr::overwrite($data, $_POST);
        $this->user = ORM::factory('user');
        if (!$this->user->validate($data))
          $errors = $data->errors();
        else {
          // логинимся и переходим, откуда юзер пришел
          $this->user->add(ORM::factory('role', 'login'));
          if ($this->user->save())
            url::redirect(url::base(FALSE).'auth/profile');
            else 
              $errors['register'] = 'Ошибка создания пользователя';
        }
    }
    $this->template->content = new View('auth/register');
    $this->template->content->errors = $errors;
    $this->template->content->postdata = is_object($data) ? $data->as_array() : $data;
  }

  public function profile() {
    $this->user OR url::redirect(url::base(FALSE).'auth/login');
    $this->template->title = 'Профиль пользователя '.$this->user->username;
    $this->template->content = new View('auth/profile');
    $this->template->content->errors = array();
    $userdata = ORM::factory('user_detail', $this->user->id);
    $this->template->content->userdata = arr::merge($this->user->as_array(), $userdata->as_array());
  }

  public function change_profile($id = NULL) {
      $this->user OR url::redirect(url::base(FALSE).'auth/login');
      $errors = $data = array();
      $userdata = ORM::factory('user_detail', $this->user->id);
      if ($this->input->post()) {
        // введены данные формы
        $data = array(
          'first_name' =>   '',
          'last_name' =>    '',
          'middle_name' =>  '',
          'city' =>         '',
          'interests' =>    '',
          'about' =>        '',
          'website' =>      '',
          'icq' =>          '',
          'jabber' =>       '',
        );
        $data = arr::overwrite($data, $_POST);
        if (!$userdata->validate($data)) {
          $errors = $data->errors();
        }
        else {
          $userdata->user_id = $this->user->id;
          if ($userdata->save())
            $errors['Result'] = 'Change_profile.Succesfull';
          else $errors['Result'] = 'Change_profile.Error';
        }
      }
      $this->template->content = new View('auth/edit_profile');
      $this->template->title = 'Ваша анкета';
      $this->template->content->userdata = arr::overwrite(arr::merge($this->user->as_array(), $userdata->as_array()), $data);
      $this->template->content->errors = $errors;
    }
}
